import { GlobalData } from '/store/state'
import { $event } from '/utils'
import { mallApi } from '/api/mall'
Page({
  data: {
    navigationHeight: GlobalData.navigationHeight,
    list: [] as GetCompaniesReturn[],
    show: true,
    value: '',
    page: 1,
    isLastPage: false,
  },
  async onLoad() {
    $event.on('after:boot', this, () => {
      this.setData({ navigationHeight: GlobalData.navigationHeight })
    })
    this.getCompany({ is_popular: 1, page: 1 })
  },
  async getCompany(pramas: GetCompaniesParams, loadMore = false) {
    wx.showLoading({
      title: '加载中',
    })
    const list = await mallApi.getCompanies(pramas)
    const isLastPage =
      this.data.page === list.meta.last_page || this.data.page > list.meta.last_page
    this.setData({
      list: loadMore ? [...this.data.list, ...list.data] : list.data,
      isLastPage,
      page: list.meta.current_page,
    })
    wx.hideLoading()
  },
  chooseCompany(e: WechatMiniprogram.CustomEvent) {
    const pages = getCurrentPages()
    const lastpage = pages[pages.length - 2]
    lastpage.setData({
      company: e.currentTarget.dataset.info.name,
      companyId: e.currentTarget.dataset.info.id,
    })
    wx.navigateBack({ delta: 1 })
  },
  onReachBottom() {
    if (this.data.isLastPage) {
      wx.showToast({
        title: '已没有更多了',
        icon: 'none',
        duration: 1000,
      })
      return
    }
    this.getCompany({ keyword: this.data.value, page: this.data.page + 1 }, true)
  },
  onInput(e: WechatMiniprogram.Input) {
    this.setData({
      value: e.detail.value,
    })
    e.detail.cursor > 0
      ? this.getCompany({ keyword: e.detail.value, page: 1 })
      : this.getCompany({ is_popular: 1, page: 1 })
  },
  onFocus() {
    if (this.data.value) return
    this.setData({
      list: [],
    })
  },
})
